# coding: utf-8
from typing import Union

from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QHBoxLayout
from qeventmanager import qevent_manager
from qfluentwidgets import SubtitleLabel, BodyLabel, TransparentToolButton, FluentIcon

from common.server import BananaServer
from components import GridScrollArea, VideoCard
from ..tools import check_result


class MoreInterface(GridScrollArea):
    closeSignal = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.spid = None
        self.horizontalLayout = QHBoxLayout(self)
        self.returnBtn = TransparentToolButton(FluentIcon.RETURN, self)
        self.titleLabel = SubtitleLabel(self)
        self.contentLabel = BodyLabel(self)

        self.contentLabel.setTextColor(QColor(0, 0, 0, 150), QColor(255, 255, 255, 150))
        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addWidget(self.returnBtn)
        self.horizontalLayout.addWidget(self.titleLabel)
        self.horizontalLayout.addWidget(self.contentLabel)

        self.returnBtn.setFixedSize(40, 36)
        self.returnBtn.clicked.connect(self._onClose)
        self.setViewportMargins(11, self.horizontalLayout.sizeHint().height(), 11, 11)

    def setTitle(self, title: str):
        self.titleLabel.setText(title)

    def setContent(self, content: str):
        self.contentLabel.setText(content)

    def _onClose(self):
        self.close()
        self.closeSignal.emit()

    def load(self, spid: Union[str, int]):
        if self.spid == spid:
            return
        self.show()
        self.spid = spid
        self.clear()
        qevent_manager.addTask(BananaServer.detail, spid, slot=self.onSetDataToPage)

    def onSetDataToPage(self, result: dict):
        data = check_result(result)
        if data is None:
            return
        spname = data['row']['spname']
        intro = data['row']['intro']
        self.setTitle(spname)
        self.setContent(intro)
        vodrows = data.get('vodrows', [])
        for vodrow in vodrows:
            if vodrow['isvip'] != '0':
                continue
            card = VideoCard(self)
            card.setData(vodrow)
            self.gridLayout.addWidget(card)
